package com.guiji.text2video.fastvideo.service.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guiji.text2video.fastvideo.config.NewsCategoryConfig;
import com.guiji.text2video.fastvideo.domain.vo.*;
import com.guiji.text2video.fastvideo.mapper.Text2videoComposeTaskMapper;
import com.guiji.text2video.fastvideo.mapper.Text2videoJobMapper;
import com.guiji.text2video.fastvideo.mapper.Text2videoNewsSessionMapper;
import com.guiji.text2video.fastvideo.service.IText2videoJobService;
import com.guiji.text2video.fastvideo.service.IText2videoTtsTaskService;
import com.guiji.text2video.fastvideo.utils.Enums;
import com.guiji.text2video.fastvideo.utils.GeneratID;
import com.guiji.text2video.fastvideo.utils.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@RefreshScope
@Service
public class VideoComposeService {

    private static final Logger logger = LoggerFactory.getLogger(VideoComposeService.class);

    @Value("${file-cache.task-video-dir}")
    private String taskVideoPath;

    @Value("${file-cache.task-video-url}")
    private String taskVideoUrl;

    @Value("${file-cache.composeVideo-url}")
    private String composeVideoUrl;

    @Value("${file-cache.composeVideo-news-url}")
    private String composeVideoNewsUrl;

    @Value("${file-cache.composeVideo-timeout}")
    private int composeVideoTimeOut;

    @Value("${file-cache.wav-dir}")
    private String wavDir;

    @Value("${file-cache.news-create-url}")
    private String newsCreateUrl;

    @Value("${file-cache.news-add-url}")
    private String newsAddUrl;

    @Value("${file-cache.news-youtubo-rtmp}")
    private String newsYouTube;

    @Value("${file-cache.news-default-video}")
    private String newsDefaultVideo;

    @Value("${file-cache.news-timeout}")
    private int newsTimeOut;

    @Value("${spring.profiles.active}")
    private String env;

    @Autowired
    IText2videoTtsTaskService ttsTaskService;
    @Autowired
    IText2videoJobService jobService;
    @Autowired(required = false)
    Text2videoJobMapper jobMapper;
    @Autowired(required = false)
    Text2videoComposeTaskMapper composeTaskMapper;
    @Autowired(required = false)
    Text2videoJobMapper text2videoJobMapper;

    @Autowired(required = false)
    Text2videoNewsSessionMapper newsSessionMapper;

    @Autowired
    private IText2videoJobService text2videoJobService;

    @Autowired
    private NewsCategoryConfig config;

    /**
     * @descp: 新闻合成线程
     * @param: 分句;job值
     * @Author: scl
     * @Date: 2021/7/22 16:44
     */
    @Async("asyncComposeVideoNewsServiceExecutor")
    public void videoComposeNews(ArrayList<Sentence> sentenceList, Text2videoJob job) throws InterruptedException {

        //1,获取tts集合
        Text2videoTtsTask tts = new Text2videoTtsTask();
        tts.setJobId(job.getJobId());
        List<Text2videoTtsTask> ttsList = ttsTaskService.selectText2videoTtsTaskList(tts);
        //2,初始化请求body
        String requestParam = initRequest(sentenceList, job, ttsList);
        //3，记录任务合成状态
        initComposeVideoTask(job, requestParam);
        //4，获取可用链接
        String composeUrl = null;
        if (config.getUrlList().size() > 0) {
            composeUrl = config.getUrlList().get(0);
            config.getUrlList().remove(0);
            logger.info("新闻获取合成服务链接大小:{},取出链接:{},job_id:{}", config.getUrlList().size(), composeUrl + job.getBackup5(), job.getJobId());
        } else {
            logger.error("新闻无法获取合成链接:{},当前线程休眠60秒。", job.getJobId());
            Thread.sleep(60000);
            return;
        }
        //5,执行合成请求
        String url = composeUrl + job.getBackup5();
        job.setBackup5(url);
        HttpResponse httpResponse = null;
        try {

            httpResponse = HttpRequest.post(url).timeout(3600000).body(requestParam).executeAsync();
        } catch (Exception e) {
            //遇到异常停顿30秒，合成重启。
            logger.info("新闻合成异常使用endpoint:{}", url);
            //执行重启
            /**
             * @descp: 358 :   {"args":["aibase_ffmpeg"]}
             * 360 :   {"args":["aibase_ffmpeg"]}
             * 362 :   {"args":["dh_video","news_studio","newsvideo","aibase_ffmpeg"]}
             * {"args":["dh_video","news_studio","newsvideo"]}
             * 127.0.0.1:20001/call/501
             * @param: videoComposeNews
             * @Author: scl
             * @Date: 2021/11/4 9:22
             */
            try {
                String restart = "{\"args\":[\"dh_video\",\"news_studio\",\"newsvideo\"]}";
                HttpRequest.post(composeUrl + "501").timeout(60000).body(restart).executeAsync();
                String ffmpeg = "{\"args\":[\"aibase_ffmpeg\"]}";
                HttpRequest.post(composeUrl + "501").timeout(60000).body(ffmpeg).executeAsync();
            } finally {
                logger.info("等待2分钟:{}", url);
                Thread.sleep(120000);
                logger.info("执行重启并且放回url:{}", url);
            }

        } finally {
            config.getUrlList().add(composeUrl);
            logger.info("新闻获取合成服务链接大小:{},放回链接:{},job_id:{}", config.getUrlList().size(), url, job.getJobId());

        }

        String videoPath = taskVideoPath;
        videoPath = videoPath.replace("taskVideos", "news");
        FileUtil.mkdir(videoPath);

        //7,nginx转发的路径
        String nginxUrl = taskVideoUrl + job.getJobId() + ".mp4";
        nginxUrl = nginxUrl.replace("taskVideos", "news");
        File saveFile = FileUtil.file(videoPath, job.getJobId() + ".mp4");
        //8，更新job状态，存储视屏流到本地
        if (httpResponse.getStatus() == Enums.numSign.len200.getKey()) {
            BufferedOutputStream outputStream = FileUtil.getOutputStream(saveFile);
            httpResponse.writeBody(outputStream, true, null);
            job.setIsSuccess(Enums.JobSign.SUCCESS.getKey());
            job.setBackup2(nginxUrl);
            job.setEndTime(new Date());
            jobMapper.updateText2videoJob(job);
            //6,不管成功与否，都要清空TTS数据
            if ("prod".equals(env)) {
                deleteTTSAndWav(job, ttsList);
            }
        } else {
            logger.info("合成失败：{}", httpResponse.toString());
            job.setIsSuccess(Enums.JobSign.COM_FAILED.getKey());
            text2videoJobMapper.updateText2videoJob(job);
            //终止推流
            return;
        }
        //3,初始化session
        //String sessionId = getAbledSession();

        //4,推送视频直播流
        // PushVideoVO(job, nginxUrl, sessionId);

        //5,删除文件,保留10以上的视频
/*        if (job.getRetrySize() < 10) {
            FileUtil.del(saveFile);
        }*/


    }


    /**
     * @descp: 取出直播可用session
     * @param:
     * @Author: scl
     * @Date: 2021/7/29 13:48
     */
    public String getAbledSession() {
        String sessionId = "";
        Text2videoNewsSession session = new Text2videoNewsSession();
        session.setRtmp(newsYouTube);
        session.setUrl(newsDefaultVideo);
        List<Text2videoNewsSession> listSessions = newsSessionMapper.selectText2videoNewsSessionList(session);
        if (ObjectUtils.isEmpty(listSessions)) {
            sessionId = getNewSession(session);
            logger.info("数据库中不存在，新建session：{}", sessionId);
            return sessionId;
        } else {
            sessionId = listSessions.get(0).getSessionId();

        }
        return sessionId;
    }

    /**
     * @descp: 推送-直播视频流
     * @param:
     * @Author: scl
     * @Date: 2021/7/21 16:48
     */
    private int PushVideo(Text2videoJob job, String pathUrl, String sessionId) {
        PushOnlineVideo pushOnlineVideo = new PushOnlineVideo();
        pushOnlineVideo.setUrl(pathUrl);
        pushOnlineVideo.setNewsCategory(job.getBackupText());
        pushOnlineVideo.setPriority(job.getRetrySize());
        pushOnlineVideo.setNewsSourceUrl(job.getBackup5());
        pushOnlineVideo.setNewsPublicTime(job.getEndTime());
        HttpResponse pushResponse = HttpRequest.post(newsAddUrl + sessionId).timeout(newsTimeOut).body(JSONUtil.parseObj(pushOnlineVideo).toString()).executeAsync();
        if (pushResponse.getStatus() == Enums.numSign.len200.getKey()) {
            logger.info("新闻视频推送成功,使用session:{},新闻内容:{}", sessionId, JSONUtil.parseObj(pushOnlineVideo).toString());
            //优先级10以上，保留历史backup4中
            if (job.getRetrySize() > 9) {
                job.setBackup4(JSONUtil.parseObj(pushOnlineVideo).toString());
                jobService.updateText2videoJob(job);
            }
        }
        return pushResponse.getStatus();
    }

    /**
     * @descp: 获取一个新的session, 并且存入表中
     * @param: String
     * @Author: scl
     * @Date: 2021/7/21 16:41
     */
    private String getNewSession(Text2videoNewsSession session) {
        String sessionId = "session";
        HttpResponse sessionResponse = HttpRequest.post(newsCreateUrl).timeout(newsTimeOut).body(JSONUtil.parseObj(session).toString()).executeAsync();
        if (sessionResponse.getStatus() == Enums.numSign.len200.getKey()) {
            sessionId = JSONObject.parseObject(sessionResponse.body()).getString("session_id");
            session.setSessionId(sessionId);
            session.setCreateTime(new Date());
            newsSessionMapper.insertText2videoNewsSession(session);
        } else {
            logger.error("初始化session失败：{}", sessionResponse.body());
        }

        return sessionId;
    }

    @Async("asyncComposeVideoServiceExecutor")
    public void videoCompose(ArrayList<Sentence> aList, Text2videoJob job) throws InterruptedException {
        Text2videoTtsTask tts = new Text2videoTtsTask();
        tts.setJobId(job.getJobId());
        List<Text2videoTtsTask> ttsList = ttsTaskService.selectText2videoTtsTaskList(tts);
        String requestParam = initRequest(aList, job, ttsList);
        initComposeVideoTask(job, requestParam);

        String url = getRequestUrl(job, composeVideoUrl);
        if (ObjectUtils.isEmpty(url)) {
            return;
        }

        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpRequest.post(url).timeout(composeVideoTimeOut).body(requestParam).executeAsync();
        } catch (Exception e) {
            throw new HttpException("合成服务链接拒绝");
        }
        String videoPathWithZip = taskVideoPath;
        if (ObjectUtils.isNotEmpty(job.getZipId())) {
            videoPathWithZip = videoPathWithZip.replace("taskVideos", job.getZipId());
            FileUtil.mkdir(videoPathWithZip);
        }
        //只删除生产环境缓存数据
        if ("prod".equals(env)) {
            deleteTTSAndWav(job, ttsList);
        }
        if (httpResponse.getStatus() == Enums.numSign.len200.getKey()) {
            BufferedOutputStream outputStream = FileUtil.getOutputStream(FileUtil.file(videoPathWithZip, job.getJobId() + "-" + job.getTitle() + ".mp4"));
            httpResponse.writeBody(outputStream, true, null);
            String pathUrl = taskVideoUrl + job.getJobId() + "-" + job.getTitle() + ".mp4";
            if (ObjectUtils.isNotEmpty(job.getZipId())) {
                pathUrl = pathUrl.replace("taskVideos", job.getZipId());
            }
            upComposeVideoTask(job, pathUrl, Enums.JobSign.SUCCESS.getKey());
        } else {
            execptionComposeVideo(job, httpResponse);

        }
    }


    /**
     * @descp: 异常处理-重试机制-记录错误
     * @param: Text2videoJob job,HttpResponse httpResponse
     * @Author: scl
     * @Date: 2021/7/20 15:56
     */
    private void execptionComposeVideo(Text2videoJob job, HttpResponse httpResponse) {
        logger.error("合成视频失败,job_id:{},job类型:{},body:{}", job.getJobId(), job.getTtsType(), httpResponse.body());
        if (httpResponse.body().contains("too much video to process")) {
            //清空历史表nlp,tts,compose,保留job表
            jobService.deleteJobHistoryNlpTTSCompose(job.getJobId());
            //job表改为-5
            job.setIsSuccess(Enums.JobSign.UNCOMMITTED.getKey());
            if (ObjectUtils.isEmpty(job.getRetrySize())) {
                job.setRetrySize(1);
            } else {
                job.setRetrySize(job.getRetrySize() + Enums.numSign.one.getKey());
            }
            text2videoJobMapper.updateText2videoJob(job);
        } else {
            upComposeVideoTask(job, httpResponse.body(), Enums.JobSign.NLP_FAILED.getKey());
        }
    }

    /**
     * @descp: 多个合成服务-选择当前可用服务,方法
     * @param: Text2videoJob job,String url
     * @Author: scl
     * @Date: 2021/7/20 15:57
     */
    private synchronized String getRequestUrl(Text2videoJob job, String url) throws InterruptedException {
        int count = 0;
        if (url.contains(",")) {
            //说明当前服务不可使,等待
            while (true) {
                String[] stirs = url.split(",");
                for (String str : stirs) {
                    if (getComposeVideoTNum(str) > 0) {
                        return str;
                    }
                }
                //服务不可用，强制退出
                if (count == 1000) {
                    //等待合成超时
                    upComposeVideoTask(job, "等待1000秒超时", Enums.JobSign.COM_FAILED.getKey());
                    return null;
                }
                Thread.sleep(Enums.numSign.TTSSleepTime.getKey());
                count++;
            }
        } else {
            return url;
        }
    }

    private int getComposeVideoTNum(String composeVideoUrl) {
        String requestParam = "{\"cmd\":\"concurrentCap\"}";
        HttpResponse httpResponse = HttpRequest.post(composeVideoUrl).timeout(composeVideoTimeOut).body(requestParam).executeAsync();
        if (httpResponse.getStatus() == Enums.numSign.len200.getKey()) {
            System.out.println(httpResponse.body());
            JSONObject jsonObject = JSON.parseObject(httpResponse.body());
            return jsonObject.getInteger("cap");
        }

        return 0;
    }


    public void upComposeVideoTask(Text2videoJob job, String pathUrl_Error, String sign) {
        Text2videoComposeTask cvt = new Text2videoComposeTask();
        cvt.setJobId(job.getJobId());
        cvt.setEndTime(new Date());
        if (Enums.JobSign.SUCCESS.getKey().equals(sign)) {
            cvt.setIsSuccess(Enums.JobSign.SUCCESS.getKey());
            //路径
            cvt.setBackup1(pathUrl_Error);
        } else {
            if (pathUrl_Error.length() > Enums.numSign.len256.getKey()) {
                //防止错误字节超过存储
                pathUrl_Error = pathUrl_Error.substring(Enums.numSign.zero.getKey(), Enums.numSign.len256.getKey());
            }
            cvt.setIsSuccess(Enums.JobSign.NLP_FAILED.getKey());
            //错误
            cvt.setBackup1(pathUrl_Error);
        }
        composeTaskMapper.updateText2videoComposeTask(cvt);

        Text2videoJob text2videoJob = new Text2videoJob();
        if (Enums.JobSign.SUCCESS.getKey().equals(sign)) {
            text2videoJob.setIsSuccess(Enums.JobSign.SUCCESS.getKey());
            //路径
            text2videoJob.setBackup2(pathUrl_Error);
        } else {
            //表示合成失败
            text2videoJob.setIsSuccess(Enums.JobSign.COM_FAILED.getKey());
            //错误，且已经被限制256字节
            text2videoJob.setBackup2(pathUrl_Error);
        }
        text2videoJob.setJobId(job.getJobId());
        text2videoJob.setEndTime(new Date());
        jobMapper.updateText2videoJob(text2videoJob);

    }

    private void deleteTTSAndWav(Text2videoJob job, List<Text2videoTtsTask> ttsList) {
        ttsList.forEach(e -> {
            String fileName = FileUtil.getName(e.getWavPath());
            FileUtil.del(wavDir + fileName);
        });
        //ttsTaskService.deleteText2videoTtsTaskById(job.getJobId());
        jobService.deleteJobHistoryNlpTTSCompose(job.getJobId());
    }

    private void initComposeVideoTask(Text2videoJob job, String requestParam) {
        Text2videoComposeTask cvt = new Text2videoComposeTask();
        cvt.setComposeId(GeneratID.getComposeGeneratID());
        cvt.setJobId(job.getJobId());
        cvt.setCreateTime(new Date());
        cvt.setIsSuccess(Enums.JobSign.RUNNING.getKey());
        cvt.setRequestText(requestParam);
        composeTaskMapper.insertText2videoComposeTask(cvt);
        if (ObjectUtils.isEmpty(job.getZipId())) {
            job.setIsSuccess(Enums.JobSign.RUN_COM.getKey());
            text2videoJobService.updateText2videoJob(job);
        }
    }

    /**
     * @descp: 合成请求json体，添加特效参数。
     * @param: "picGenType":"http_GaussianBlur",高斯模糊
     * @Author: scl
     * @Date: 2022/1/19 17:03
     */
    private String initRequest(ArrayList<Sentence> aList, Text2videoJob job, List<Text2videoTtsTask> ttsList) {
        ComposeVideoRequestVO cvr = new ComposeVideoRequestVO();
        cvr.setTaskId(job.getJobId());
        cvr.setTitle(job.getTitle());
        cvr.setSentences(aList);

        int totalMill = 0;
        for (Sentence ele : cvr.getSentences()) {
            ele.setPicGenType(job.getTtsLanguage());
            long duration = 0L;
            for (String sen : ele.getSentences()) {
                for (Text2videoTtsTask tts : ttsList) {
                    if (tts.getWavText().equals(sen)) {
                        ele.getWavs().add(tts.getWavPath());
                        //添加记录时间
                        duration += (long) (Convert.toDouble(tts.getWavDuration()) * 1000);
                        break;
                    }
                }
            }
            ele.setDuration(duration);
            totalMill = (int) (totalMill + duration);
        }
        cvr.setMillseconds(totalMill);
        // 删除video操作
        filterVideos(cvr);
        //添加背景音乐
        if (StrUtil.isNotEmpty(job.getBackup3()) && job.getBackup3().contains(".mp3")) {
            cvr.setBgm(CollUtil.newArrayList(job.getBackup3()));
        } else if (StrUtil.isNotEmpty(job.getBackup3()) && job.getBackup3().contains("http") && !job.getBackup3().contains(".mp3")) {
            //随机某个类别
            cvr.setBgm(CollUtil.newArrayList(getRandom(job.getBackup3())));
        }

        //判断新闻
        boolean isNews = ("-1".equals(job.getTtsType()) || "-3".equals(job.getTtsType()));

        if (isNews) {
            // 图片填充逻辑
            getPicsNotDe(cvr, job);
            // getPics(cvr);
        }

        //添加数字人，竖屏参数

        boolean isHuman = ("362".equals(job.getBackup5()) || "360".equals(job.getBackup5()));

        if (isHuman) {
            String jsonStr = JSONUtil.parseObj(cvr).toString();
            jsonStr = jsonStr.substring(0, jsonStr.length() - 1) + "," + job.getBackup2() + "}";
            return jsonStr;
        } else {
            return JSONUtil.parseObj(cvr).toString();
        }

    }

    private String getRandom(String path) {
        //String str = "http://172.16.160.55/text2video/bgm/calm-17";

        String categoryBgm = FileNameUtil.getName(path);
        String num = categoryBgm.split("-")[1];
        String result = path + "/" + RandomUtil.randomInt(0, Integer.parseInt(num)) + ".mp3";
        return result;
    }


    private void getPicsNotDe(ComposeVideoRequestVO cvr, Text2videoJob job) {

        //计算job中content内容中#1#，#2#的位置。
        String pics = job.getBackup4();
        pics.replace("\"", "");
        String[] arrayPics = pics.split(",");

        //按时长平均
        int sSize = cvr.getSentences().size();
        int pSize = arrayPics.length;

        if (sSize > pSize) {
            //段落比图片多，将图片复制多份,向上取整。
            List<Integer> numList = new ArrayList<Integer>();
            for (int k = 0; k < pSize; k++) {
                int max = (int) Math.ceil(sSize / pSize);
                for (int m = 0; m < max; m++) {
                    numList.add(k);
                }
            }
            int temp = numList.size();
            if (temp < sSize) {
                for (int m = 0; m < sSize - temp; m++) {
                    numList.add(pSize - 1);
                }
            }

            for (int a = 0; a < sSize; a++) {
                cvr.getSentences().get(a).setImages(ListUtil.toList(arrayPics[numList.get(a)]));
            }
        } else {
            //图片大于段落
            for (int a = 0; a < sSize; a++) {
                cvr.getSentences().get(a).setImages(ListUtil.toList(arrayPics[a]));
            }
        }

/*        if (job.getContent().contains("#1#")) {
            String content = job.getContent();
            int totalTime = cvr.getMillseconds();

            int lengthContent = content.length();
            List<Integer> picNumbers = new ArrayList<Integer>();
            for (int k = 1; k <= pSize; k++) {
                String sign = "#" + k + "#";
                int a = totalTime * content.split(sign)[0].length() / lengthContent;
                picNumbers.add(a);
            }

            //计算每段音频时长的范围
            List<Integer> numList = new ArrayList<Integer>();

            int currentTime = 0;
            for (int m = 0; m < sSize; m++) {
                Long every = cvr.getSentences().get(m).getDuration();
                int everyTime = Integer.parseInt(every + "");
                currentTime = currentTime + everyTime;

                logger.info("第"+m+"段时间长度:{}",m,currentTime);
                for (int q = 0; q < pSize; q++) {
                    if (currentTime <= picNumbers.get(0)) {
                        numList.add(0);
                        break;
                    }
                    if (q + 1 <= pSize && picNumbers.get(q) < currentTime && picNumbers.get(q + 1) >= currentTime) {
                        numList.add(q);
                        break;
                    }
                    if (currentTime > picNumbers.get(pSize)) {
                        numList.add(pSize);
                        break;
                    }

                }

            }

            logger.info("totalTime:{},sSize:{},pSize:{}",totalTime,sSize,pSize);
            //打印坐标
            for(int a:picNumbers){
                logger.info("图片所在的时间长度：{}",a);
            }
            for(int a:numList){
                logger.info("段落所属的图片下标：{}",a);
            }


        }else{
        }*/
    }


    private void getPics(ComposeVideoRequestVO cvr) {

        int gap = 20000;
        int totalMill = cvr.getMillseconds();
        int longSize = (totalMill / gap) + 100;
        ArrayList<String> pics = new ArrayList<>();

        while (true) {
            if (cvr.getSentences().size() < 2) {
                break;
            }
            //形成一个长的图片列表
            for (Sentence ele : cvr.getSentences()) {
                if (ele.getIndex() > 1) {
                    pics.addAll(ele.getImages());
                }
            }
            if (pics.size() == 0) {
                break;
            }
            if (pics.size() > longSize) {
                break;
            }
        }
        //logger.info("pics长度：{},longSize：{}",pics.size(),longSize);
        //分割每段内容，分割图片
        int label = 0;
        for (Sentence ele : cvr.getSentences()) {
            if (ele.getIndex() > 1) {

                //向上取整，保证0-4秒，都有一张图片
                int size = (int) Math.ceil((double) ele.getDuration() / gap);
                //logger.info("每段长度：{}，使用index:{}",size,ele.getIndex());
                //重新赋值图片内容,$SubList cannot be cast to java.util.ArrayList
                List<String> list = pics.subList(label, label + size);
                ArrayList<String> tmpList = new ArrayList<>();
                for (String e : list) {
                    tmpList.add(e);
                }
                ele.setImages(tmpList);
                label = label + size;
            }
        }
    }

    private void filterVideos(ComposeVideoRequestVO request) {
        HashSet<String> videoSets = CollUtil.newHashSet();
        for (Sentence sentence : request.getSentences()) {
            int index = sentence.getIndex();
            if (index == 1) {
                continue;
            }
            // 增加2s的空余量
            long duration = sentence.getDuration() + 2000;
            Long videoDuration = 0L;
            ArrayList<String> videoList = CollUtil.newArrayList();
            for (int i = 0; i < sentence.getVideoDurations().size(); i++) {
                long dura = Convert.toLong(sentence.getVideoDurations().get(i));
                String url = sentence.getVideos().get(i);
                if (videoDuration > duration) {
                    break;
                }
                if (!videoSets.contains(url)) {
                    videoDuration = videoDuration + dura;
                    videoList.add(url);
                    videoSets.add(url);
                }
            }
            if (CollUtil.isEmpty(videoList) || videoDuration < duration) {
                videoList.addAll(sentence.getVideos());
            }
            sentence.setVideos(videoList);
            sentence.setVideoDurations(null);
        }
    }
}
